<template>
  <div class="bufferContainer">
    <el-dialog v-model="dialogVisible" width="15%">
      <span style="font-size: 140%">是否跳转至{{ nextBuilding }}</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="toBuilding"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 标题 -->
    <div class="bufferTitle">场所设施概况</div>
    <!-- 内容 -->
    <div v-for="(list, index) in tableData" :key="index" class="bigBox">
      <p @click="showChange">{{ list.title }}</p>
      <div class="box" @transitionend="transitionendHandler">
        <div
          v-for="(data, index) in list.children"
          :key="index"
          class="generalBox"
        >
          <img
            :src="require('@/assets/设施场所icon/定位.png')"
            @click="click"
          />
          <span class="key">{{ data.key }}</span>
          <span class="value">{{ data.value }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/*eslint-disable */
import pubsub from "pubsub-js";
import { getCurrentInstance, onMounted } from "vue-demi";
import axios from "axios";
import url from "@/components/URL.json";
import buildingList from "@/json/裕兴花园房屋面.json";
import { useRouter } from "vue-router";

export default {
  name: "buildingBuffer",
  data() {
    return {
      nextBuilding: "楼栋",
      dialogVisible: false,
      tableData: [
        {
          title: "摄像头",
          children: [
            {
              key: "A15119",
              value: "进港大道54号南沙街社区卫生服务",
            },
            {
              key: "A15120",
              value: "进港大道54号",
            },
            {
              key: "H2410",
              value: "金沙路26号-裕兴花园金基城墙角人",
            },
          ],
        },
        {
          title: "文体设施",
          children: [
            {
              key: "老人活动中心",
              value: "南沙区南沙街金洲村惠康街金沙路北侧老人活动中心",
            },
            {
              key: "中共金洲村支部委员会",
              value: "进港大道52号附近",
            },
          ],
        },
      ],
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    // 缓冲距离
    let bufferDistance = 0.0006;
    let subList = [];
    let poiList = [];
    let neighbourBuilding = [];
    let height;
    let nextBuilding = {};

    onMounted(() => {
      // //   传入新楼栋
      // subList[0] = pubsub.subscribe("bufferCenter", (n, centerPoint) => {
      //   proxy.tableData = [];
      //   //读取poi重要信息
      //   getPoiLocation().then((poi) => {
      //     // 距离匹配楼栋
      //     distanceMatchBuilding(centerPoint);
      //     // 距离匹配POI
      //     distanceMatchPOI(centerPoint, poi).then((list) => {
      //       // 备份
      //       poiList = list;
      //       console.log(centerPoint, poi, list);
      //       // 添加poi至地图
      //       pubsub.publish("addBufferPOI", list);
      //       // poi信息填入
      //       poiDataInput(list);
      //     });
      //   });
      // });
      // //退出旧楼栋
      // subList[1] = pubsub.subscribe("returnFromBuilding", () => {
      //   pubsub.publish("deleteBufferPOI", poiList);
      //   // pubsub.publish("optionRenew", "人口信息");
      // });
      // //   退出楼栋周边界面
      // subList[2] = pubsub.subscribe("quitBuffer", () => {
      //   pubsub.publish("deleteBufferPOI", poiList);
      // });
    });

    //读取所有POI的重要信息
    function getPoiLocation() {
      let arr = [];
      let dbNameList = ["安防科技", "基础设施", "停车场", "重点场所"];
      return new Promise((reslove) => {
        for (let i = 0; i < dbNameList.length; i++) {
          axios({
            method: "get",
            url: url.basicURL + "getFacility",
            params: { db: "3d_" + dbNameList[i] },
          }).then((res) => {
            arr.push(res.data);
            if (arr.length === 4) reslove(arr);
          });
        }
      });
    }

    // POI距离匹配
    function distanceMatchPOI(centerPoint, poi) {
      let selection = [];
      //遍历匹配
      return new Promise((reslove) => {
        for (let i = 0; i < poi.length; i++) {
          poi[i].forEach((element) => {
            let distance = Math.sqrt(
              Math.pow(Number(element["84Lat"]) - centerPoint["y"], 2) +
                Math.pow(Number(element["84Lng"]) - centerPoint["x"], 2)
            );
            if (distance < bufferDistance) selection.push(element);
          });
          if (i === poi.length - 1) reslove(selection);
        }
      });
    }

    // 楼栋距离匹配
    function distanceMatchBuilding(centerPoint) {
      let selection = [];
      buildingList.features.forEach((element) => {
        let distance = Math.sqrt(
          Math.pow(element.attributes["X"] - centerPoint.x, 2) +
            Math.pow(element.attributes["Y"] - centerPoint.y, 2)
        );
        if (distance < bufferDistance) selection.push(element);
      });
      neighbourBuilding = selection;
      //   楼栋信息填入
      let arr = [];
      selection.forEach((element) => {
        arr.push({
          key: element.attributes["XXDZ"].split("号")[1],
          value: element.attributes["XXDZ"],
        });
      });
      proxy.tableData.push({
        title: "附近楼栋",
        children: arr,
      });
    }

    //poi信息填入
    function poiDataInput(features) {
      // 地物类型整合
      let lbList = [features[0]["LB"]];
      let lb = features[0]["LB"];
      features.forEach((feature) => {
        if (feature["LB"] != lb) {
          let isNew = true;
          lbList.forEach((element) => {
            if (element === feature["LB"]) isNew = false;
          });
          if (isNew) {
            lbList.push(feature["LB"]);
            lb = feature["LB"];
          }
        }
      });
      //   console.log(lbList);
      lbList.forEach((element) => {
        let arr = [];
        features.forEach((feature) => {
          if (feature.LB === element) {
            // 摄像头
            if (feature.LB === "摄像头") {
              arr.push({ key: feature["MC"] });
            }
            // 公交站
            else if (feature.LB === "交通设施") {
              arr.push({ key: feature["MC"] });
            }
            // 停车场
            else if (feature.LB === "停车场") {
              arr.push({
                key: feature["MC"],
                value: feature["XXDZ"].split("沙区")[1],
              });
            }
            // 防疫卡口
            else if (feature.LB === "防疫卡口") {
              arr.push({
                key: "防疫卡口",
                value: feature["MC"].split("防疫卡口")[0],
              });
            }
            // 其他
            else {
              arr.push({
                key: feature["MC"],
                value: feature["XXDZ"],
              });
            }
          }
        });
        proxy.tableData.push({
          title: element,
          children: arr,
        });
      });
    }

    //设施场所点击
    function click() {
      let poi = {};
      // 读取标题
      let title = Array.from(
        event.target.parentNode.parentNode.parentNode.children
      )[0].innerHTML;
      //   特殊类别甄别
      if (title === "附近楼栋") {
        let address = Array.from(event.target.parentNode.children)[2].innerHTML;
        neighbourBuilding.forEach((element) => {
          if (element.attributes.XXDZ === address) poi = element;
        });
      } else if (title === "摄像头") {
        let address = Array.from(event.target.parentNode.children)[1].innerHTML;
        poiList.forEach((element) => {
          if (element.XXDZ === address) poi = element;
        });
      } else if (title === "防疫卡口") {
        let address =
          Array.from(event.target.parentNode.children)[2].innerHTML +
          "防疫卡口";
        poiList.forEach((element) => {
          if (element.MC === address) poi = element;
        });
      } else if (title === "交通设施" || title === "停车场") {
        let address = Array.from(event.target.parentNode.children)[1].innerHTML;
        poiList.forEach((element) => {
          if (element.MC === address) poi = element;
        });
      } else {
        let address = Array.from(event.target.parentNode.children)[2].innerHTML;
        poiList.forEach((element) => {
          if (element.XXDZ === address) poi = element;
        });
      }
      console.log(poi);
      if (poi.attributes != undefined) {
        nextBuilding = poi;
        // 转至楼栋
        proxy.nextBuilding = Array.from(
          event.target.parentNode.children
        )[1].innerHTML;
        proxy.dialogVisible = true;
      } else {
        //转至POI
        pubsub.publish("toPOI", poi);
      }
    }

    // 设施场所类别显示控制
    function showChange() {
      let bigBox = Array.from(event.target.parentNode.children)[1];
      let title = event.target.innerHTML;
      if (bigBox.getAttribute("active") === "1") {
        bigBox.setAttribute("active", "0");
        // 重启POI
        pubsub.publish("respawnPOI", title);
      } else {
        bigBox.setAttribute("active", "1");
        //关闭POI
        pubsub.publish("POIshowOff", title);
      }
    }

    //确认楼栋跳转
    function toBuilding() {
      // 隐藏
      proxy.dialogVisible = false;
      console.log(nextBuilding);
      pubsub.publish("hierarchyQuit", "@");
      //   退出
      pubsub.publish("returnFromBuilding");
      pubsub.publish("needReturn");
      pubsub.publish("firstPageShowChange", true);
      pubsub.publish("optionRenew", "人口信息");
      pubsub.publish("needCut", true);
      // 跳转
      window.history.go(-1);
      setTimeout(() => {
        console.log("跳转");
        router.push({
          path: "/buildingSelected",
        });
        //   跳转
        pubsub.publish("buildingSelected", nextBuilding);
      }, 500);
    }

    return { subList, click, showChange, toBuilding };
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
.bufferContainer {
  height: 100%;
  overflow: hidden;
  > .bufferTitle {
    height: 5%;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 170%;
    font-weight: bold;
    background-image: ~"url(@{app-images-root}/button_bg2.png)";
    background-size: 100% 100%;
  }
  overflow-y: scroll;
  overflow-x: hidden;
}

.bufferContainer::-webkit-scrollbar {
  width: 5px;
}

.bufferContainer::-webkit-scrollbar-thumb {
  height: 25px;
  border-radius: 15px;
  background: #1296db;
}

.buildingList::-webkit-scrollbar-track {
  background: transparent;
}

.bigBox {
  > p {
    margin: 3%;
    font-size: 150%;
    font-weight: bold;
    padding: 1% 5%;
    border-radius: 3px;
    //   background-color: #1296db;
    background-image: ~"url(@{app-images-root}/button_bg6.png)";
    background-size: 100% 100%;
    color: white;
  }
}
.generalBox {
  width: 97%;
  margin: 2% 0%;
  position: relative;
  > img {
    width: 8%;
    position: relative;
    left: 2%;
  }
  > .value {
    display: inline-block;
    color: #1296db;
    font-size: 110%;
    font-weight: bold;
    margin-left: 3.5%;
  }
  > .key {
    color: white;
    position: relative;
    left: 3%;
    font-size: 140%;
    font-weight: bold;
  }
}

.generalBox > img:hover {
  cursor: pointer;
}

.box,
.box[active="0"] {
  position: relative;
  display: block;
}

.box[active="1"] {
  position: relative;
  display: none;
}
</style>